package com.example.wyj.editdemo;

import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneNumberFormattingTextWatcher;
import android.telephony.PhoneNumberUtils;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    private EditText editText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        editText = findViewById(R.id.edit_text);
        editText.addTextChangedListener(loginInputAccountWatcher);
    }

    private TextWatcher loginInputAccountWatcher = new PhoneNumberFormattingTextWatcher() {

        /**
         * @param s          变化后的文本
         * @param start      开始变化的索引
         * @param before     原字符的长度
         * @param inputCount start开始输入count个
         */
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int inputCount) { // total 12 start 11 before: 改变原来字符串的个数 input: 0 | 1
            String formatPhone;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                formatPhone = PhoneNumberUtils.formatNumber(s.toString(), Locale.getDefault().getCountry());
            } else {
                formatPhone = PhoneNumberUtils.formatNumber(s.toString());
            }
            Log.i("COCO", "phone:" + formatPhone);
//            PhoneNumberUtil pnu = PhoneNumberUtil.getInstance();
//            Phonenumber.PhoneNumber pn = pnu.parse("1234567890", "US");
//            String pnE164 = pnu.format(pn, PhoneNumberUtil.PhoneNumberFormat.E164);
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }


        @Override
        public void afterTextChanged(Editable s) {

            //editText.removeTextChangedListener(this);
            //editText.setText(formatPhone);
            //editText.addTextChangedListener(this);
        }
    };

}
